import React from "react"
import {Form,Input,Button,message} from "antd"
import "./index.css"
import { getMenu } from "../../api"
import { useNavigate,Navigate } from "react-router-dom"
import {getMenuList} from "../../store/reducers/tab"
import { useDispatch,useSelector } from "react-redux"
const Login =()=>{
    const [form] = Form.useForm()
    const  dispatch = useDispatch()
    const navigate = useNavigate()
    //在登录状态下，需要跳转到Home页面中
    //判断token是否存在，如果存在就跳转到Home页面中
    if(localStorage.getItem("token")){
        return <Navigate to="/home" replace/>
    }
    const handleSubmit = (value)=>{
        //表单提交时进行
        if(!value.username ){
           return message.open({
               type:"warning",
               content:"请输入账号"

           })
        }
        else if(!value.password){
            return message.open({
                type:"warning",
                content:"请输入密码"

            })
        }
        else if(!value.username && !value.password){
            return message.open({
                type:"warning",
                content:"请输入账号和密码"

            })
        }
        getMenu(value).then(res=>{
            console.log(res.data.menu,1234)
            //将token存到缓存中
            localStorage.setItem("token",res.data.token)
            localStorage.setItem("menu",JSON.stringify(res.data.menu))
            //获取菜单列表
            dispatch(getMenuList(res.data.menu))
            //跳转到首页
            navigate("/home")
            //清空表单
             form.resetFields()
            


        }).catch(err=>{
            console.log(err,222)
            message.open({
                type:"error",
                content:"账号或者密码错误"

            })
            form.resetFields()
        })

    }

    return(
       <Form form={form} className="login-container" onFinish={handleSubmit }>
        <div className="login-title">系统登录</div>
        <Form.Item label="账号" name="username">
            <Input placeholder="请输入账号"/>
        </Form.Item>
        <Form.Item label="密码" name="password">
            <Input.Password placeholder="请输入密码"/>
        </Form.Item>
        <Form.Item className="login-button">
            <Button type='primary' htmlType="submit">登录</Button>
        </Form.Item>
        

       </Form>
    )
}
export default Login